package com.mzw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mzw.mapper.ChartMapper;
import com.mzw.model.entity.Chart;
import com.mzw.service.ChartService;
import com.mzw.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author L1nAn
 * 定期分析失败原因
 */
@Component
@Slf4j
public class CauseAnalysisImpl {


    @Resource
    private ChartService chartService;
    @Resource
    private ChartMapper chartMapper;
    @Resource
    private EmailService emailService;
    // 每月执行一次
    @Scheduled(cron = "0 15 10 15 * ?")
    public void getCauseAnalysis() {
        // 获取一个时间内的任务总数
        int totalNums = chartMapper.getCount();
        log.info("本月任务总数：{}", totalNums);
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<Chart>();
        queryWrapper.eq("status", "failed");
        long failedNums = chartService.count(queryWrapper);
        log.info("失败总数为:{}",failedNums);
        queryWrapper.eq("execMessage", "AI 生成错误");
        long aiNums = chartService.count(queryWrapper);
        log.info("由于AI 生成错误导致任务失败的总数：{}", aiNums);
        // 得到本月由于AI失败的任务所占比例。，当超过5%时，考虑是否调整AI模型。
        boolean flag = (double) aiNums / failedNums > 0.05;
        if (flag) {
            // 利用邮箱通知
            emailService.sendEmail("Mzw_37@163.com", "系统通知", "您的系统由于AI 生成错误导致" +
                    "失败的任务已经超过正常情况，请根据情况调整AI模型");
        }

    }
}
